<?php

namespace Anchu\Restful\Runner\Decorates;

class DecorateFactory
{
    /**
     * @param $decorates FilterDecorate[]
     * @return Filter
     */
    public static function filter(array $decorates): Filter
    {
        return array_reduce($decorates, function ($filter, $decorate) {
            $obj = new $decorate();
            return $obj->run($filter);
        }, new Filter());
    }

    /**
     * 对数据进行装饰，比如说：脱敏
     * @param array $decorates
     * @param array|object $result
     * @return array|mixed|object
     */
    public static function data(array $decorates, array|object|null $result, array $options = [])
    {
        $result = is_null($result) ? $result : (is_object($result) ? $result?->toArray() : $result);
        $data = isset($result['current_page']) ? $result['data'] : $result;
        $data = is_null($data) ? [] : $data;
        $data = array_reduce($decorates, function ($data, $decorate) use ($options) {
            $obj = new $decorate();
            return $obj->run($data, $options);
        }, $data);
        if (isset($result['current_page'])) {
            $result['data'] = $data;
        } else {
            $result = $data;
        }
        return $result;
    }

    /**
     * 处理传入的参数，如：设置默认值
     * @param array $decorates
     * @param array $params
     * @param array $options
     * @return array
     */
    public static function params(array $decorates, array $params, $options = [])
    {
        if (isset($options['models'])) {
            return array_reduce($decorates, function ($params, $decorate) use ($options) {
                $obj = new $decorate();
                return $obj->run($params, $options);
            }, $params);
        }
        return $params;
    }
}
